package demo.service.impl;

import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * 内存方式的用户服务，后期可改为从数据库读取
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService  {
    private final HashMap<String, UserDetails> users = new HashMap<>();

    public UserDetailsServiceImpl(PasswordEncoder passwordEncoder) {
        User.UserBuilder builder = User.builder();
        // 普通用户 user，初始密码：123456
        UserDetails user = builder
                .username("user")
                .password(passwordEncoder.encode("123456"))
                .roles("USER")
                .build();
        // 管理员用户 admin
        UserDetails admin = builder
                .username("admin")
                .password(passwordEncoder.encode("123456"))
                .roles("ADMIN")
                .build();
        users.put("user", user);
        users.put("admin", admin);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetails user = users.get(username);
        if (user == null) {
            throw new UsernameNotFoundException(username);
        }
        return new User(user.getUsername(), user.getPassword(), user.getAuthorities());
    }
}
